package com.sayi.dzapi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;



import com.sayi.dzapi.annotation.CheckBrowser;

import com.sayi.dzapi.utils.JwtUtil;
import com.sayi.dzapi.entities.User;


@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @CheckBrowser
    // 用户登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam(value="username",required=false) String username,
                                   @RequestParam(value="password",required=false) String password) {


        // 检查用户名和密码是否为空
        if (username == null || username.trim().isEmpty()) {
            return ResponseEntity.status(400).body("Username cannot be empty.");
        }
        if (password == null || password.trim().isEmpty()) {
            return ResponseEntity.status(400).body("Password cannot be empty.");
        }





        // 验证用户名和密码
        User user = userService.authenticate(username, password);

        if (user != null) {
            int code=user.getCode();
            switch(code){
                case 200:
                    // 生成JWT
                    String token = JwtUtil.generateToken(user.getUid(),user.getUsername());
                    return ResponseEntity.ok(new AuthResponse(token));
                default:
                    return ResponseEntity.status(code).body(user.getMessage());
            }
        } else {
            return ResponseEntity.status(401).body("Invalid username or password.");
        }
    }

    @GetMapping("/test")//检查token是否有效
    public ResponseEntity<String> authTest(@RequestHeader(value="Authorization",required=false) String authorizationHeader){
        String token = null;
        if(authorizationHeader==null){
            return ResponseEntity.ok("missing auth");
        }
        if(!authorizationHeader.startsWith("Bearer ")){
            return ResponseEntity.ok("error auth");
        }
        
        token = authorizationHeader.substring(7);  // 去除 "Bearer " 前缀
        
        int userId=JwtUtil.extractUserId(token);
        // Step 2: 验证 JWT Token 是否有效
        if (token == null || !JwtUtil.validateToken(token,userId)) {
            return ResponseEntity.status(401).body("Unauthorized: Invalid or missing token.");
        }
        return ResponseEntity.ok("user "+userId+" auth passed.");
    }

    // JWT 响应类
    public static class AuthResponse {
        private String token;

        public AuthResponse(String token) {
            this.token = token;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }
    }

}
